import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_time_manager/state/db_help.dart';
import 'package:flutter_time_manager/state/model/user_info.dart';
import 'package:image_picker/image_picker.dart';

const defaultAvatar = "assets/image/avatar.jpeg";

class UserState with ChangeNotifier {
  bool _isLoading = true;

  final _dbHelp = DbHelp();

  UserInfo _userInfo;

  UserState() {
    _getUserInfo();
  }

  void _getUserInfo() async {
    final db = await _dbHelp.database;
    List<Map<String, dynamic>> list = await db
        .rawQuery("select id, avatar, name, note from user_info limit 1");
    if (list.isEmpty) {
      _userInfo = UserInfo(
          id: 1,
          avatar: defaultAvatar,
          name: "Learn peng",
          note: "永远相信美好的事情即将发生");
      db.rawInsert("""
      insert into user_info (id, avatar, name, note) 
      values (?,?,?,?)
      """, [_userInfo.id, _userInfo.avatar, _userInfo.name, _userInfo.note]);
    } else {
      _userInfo = UserInfo.fromMap(list[0]);
    }
    _isLoading = false;
    notifyListeners();
  }


  bool get isLoading => _isLoading;

  String get note => _userInfo.note;

  String get avatarImageFilePath => _userInfo == null ? defaultAvatar : _userInfo.avatar;

  String get userName => _userInfo.name;

  updateNote(String note) {
    if (note != null && note.trim().isNotEmpty) {
      _userInfo.note = note;
      _updateNote(note, _userInfo.id);
      notifyListeners();
    }
  }

  updateName(String name) {
    if (name != null && name.trim().isNotEmpty) {
      _userInfo.name = name.trim();
      _updateName(name, _userInfo.id);
      notifyListeners();
    }
  }

  replaceImage() async {
    try {
      File imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
      if (imageFile != null) {
        _userInfo.avatar = imageFile.path;
        _updateAvatar(imageFile.path, _userInfo.id);
        notifyListeners();
      }
    } catch (e) {
      print("error: ${e}");
    }
  }

  void _updateName(String name, int id) async {
    final db = await _dbHelp.database;
    await db.rawUpdate("update user_info set name = ? where id = ?", [name, id]);
  }

  void _updateAvatar(String path, int id) async {
    final db = await _dbHelp.database;
    await db.rawUpdate("update user_info set avatar = ? where id = ?", [path, id]);
  }

  void _updateNote(String note, int id) async {
    final db = await _dbHelp.database;
    await db.rawUpdate("update user_info set note = ? where id = ?", [note, id]);
  }
}
